package com.fahai.web.controller;

import com.fahai.common.AuthProvider;
import com.fahai.utils.json.JsonResult;
import com.fahai.web.entity.Menu;
import com.fahai.web.service.RoleMenuService;
import com.fahai.web.service.SysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * Created by sky on 17/5/5.
 * 登陆的控制器
 */

@Controller
public class LoginController extends BaseController {
    static Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    AuthProvider authProvider;

    @Autowired
    RoleMenuService roleMenuService;
    @Autowired
    SysUserService sysUserService;

    /**
     * 登陆页面
     *
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "login", method = RequestMethod.GET)
    public String jumpToLoginPage() {
        return "login";
//        return "login/login";
    }

    /**
     * 注册页面
     *
     * @return
     */
    @RequestMapping(value = "register", method = RequestMethod.GET)
    public String jumpToRegisterPage() {
        return "login/register";
    }

    /**
     * 跳转到主页
     *
     * @return
     */
    @RequestMapping(value = {"/", "index"}, method = RequestMethod.GET)
    public String jumpToIndexPage(Model model) {


        return "navigation_bar";
    }

    /**
     * 提交登陆信息,跳转到主页界面或登陆前访问的页面
     *
     * @param username
     * @param password
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "/submitLoginParam", method = RequestMethod.POST)
    public JsonResult submitLoginParam(@RequestParam(required = true) String username, @RequestParam(required = true) String password, HttpServletRequest request) throws IOException {
        String redirect = "/index";
        HttpSession session = request.getSession();
        // 如果是其他请求导致的login redirect, 这里可以获取到redirect之前的URL
        SavedRequest savedRequest = (SavedRequest) session.getAttribute("SPRING_SECURITY_SAVED_REQUEST");
        if (savedRequest != null) {
            redirect = savedRequest.getRedirectUrl();
        }
        if (!ObjectUtils.isEmpty(username) && !ObjectUtils.isEmpty(password)) {
            UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
            try {
                Authentication auth = authProvider.authenticate(token);
               if(null==auth){
                         return unlogin("用户名或密码错误");
                }
                if("$被冻结$".equals(auth.getName())){
                    return unlogin("用户可能被冻结或没有权限");
                }

                session.setAttribute("username", username);
                session.setAttribute("realName", sysUserService.findSysUserByUserName(username).getRealName());//设置用户真实名称 即汉子名称
                logger.debug("用户session为:"+session.getAttribute("username"));
                SecurityContextHolder.getContext().setAuthentication(auth); //保存登陆权限
            } catch (BadCredentialsException e) {
//                logger.error("login fail: ", e);
                return unlogin("用户名或密码错误");
            } catch (Exception e) {
//                logger.error("login fail: ", e);
                return unlogin("未知错误");
            }
            session.setAttribute("username", username);
            logger.debug(username + password);
        } else {
            return unlogin("请输入用户名或密码");
        }
        List<Map<String,Object>>  getRoelMenu=roleMenuService.selectUserRoleMenu(username);
        session.setAttribute("roleMenu", getRoelMenu);
        String userName=session.getAttribute("username").toString();
        List<Menu> menuList = roleMenuService.findRoleMenu(userName);

        session.setAttribute("menuList",menuList);
        return ok("登陆成功", redirect);
    }

    /**
     * 退出登录
     * 注掉采用spring security配置
     * @return
     */
//    @RequestMapping(value = "logout", method = RequestMethod.GET)
//    public String logoutPage(HttpSession session) {
//        if (!ObjectUtils.isEmpty(session)) {
//            session.invalidate();
//        }
//        return "login/login";
//    }

    /**
     * 修改密码
     *
     * @param oldPass
     * @param newPass
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "alterPassword", method = RequestMethod.PUT)
    public JsonResult alterPassword(@RequestParam String oldPass, @RequestParam String newPass) {
        return ok("修改成功");
    }
}
